package com.heima.article.service.impl;

import com.heima.article.service.ApCollectionService;
import com.heima.article.thread.AppThreadLocalUtil;
import com.heima.common.cache.CacheService;
import com.heima.common.constants.BehaviorConstants;
import com.heima.model.article.dtos.CollectionBehaviorDto;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.user.pojos.ApUser;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
@Slf4j
public class ApCollectionServiceImpl implements ApCollectionService {

    @Autowired
    private CacheService cacheService;

    @Override
    public ResponseResult collection(CollectionBehaviorDto dto) {

        if (dto == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE,"传入参数为空");
        }

        Long entryId = dto.getEntryId();
        if (entryId == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE,"文章不存在");
        }

        ApUser user = AppThreadLocalUtil.getUser();
        if (user == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.AP_USER_DATA_NOT_EXIST,"用户不存在");
        }
        Integer userId = user.getId();
        if (userId == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.AP_USER_DATA_NOT_EXIST,"用户不存在");
        }

        Short operation = dto.getOperation();
        Long currentTime = System.currentTimeMillis();
        if (operation == 0) {
            cacheService.hPut(BehaviorConstants.COLLECTION_BEHAVIOR + entryId, userId.toString(), currentTime.toString());
        }else {
            cacheService.hDelete(BehaviorConstants.COLLECTION_BEHAVIOR + entryId, userId.toString());
        }


        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }
}
